package com.tz.farmer.service.impl;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.smartPark.msframe.result.ResultEx;
import com.tz.farmer.enums.ErrorCodeEnum;
import com.tz.farmer.mapper.FarmerRoleInfoMapper;
import com.tz.farmer.mapper.FarmerUserInfoMapper;
import com.tz.farmer.mapper.RolePermissionInfoMapper;
import com.tz.farmer.model.FarmerPermissionInfo;
import com.tz.farmer.model.FarmerRoleInfo;
import com.tz.farmer.model.FarmerUserInfo;
import com.tz.farmer.model.RolePermissionInfo;
import com.tz.farmer.service.FarmerRoleInfoService;

import com.tz.farmer.so.FarmerRoleInfoSo;
import com.tz.farmer.so.FarmerUserInfoSo;
import com.tz.farmer.util.BeanConvertUtils;
import com.tz.farmer.util.ResultExM;
import com.tz.farmer.vo.FarmerRoleInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @ClassName SmartAdminRoleInfoServiceImpl
 * @Description TODO
 * @Creator kaikai
 * @Date 2021/5/11 17:15
 */
@Service
public class FarmerRoleInfoServiceImpl extends ServiceImpl<FarmerRoleInfoMapper, FarmerRoleInfo> implements FarmerRoleInfoService {

    @Resource
    FarmerRoleInfoMapper  farmerRoleInfoMapper;
    @Resource
    FarmerUserInfoMapper farmerUserInfoMapper;

    @Resource
    RolePermissionInfoImpl rolePermissionInfoImpl;

    @Resource
    RolePermissionInfoMapper rolePermissionInfoMapper;




    @Override
    public ResultEx getAdminRoleListByConditions(FarmerRoleInfoSo so) {
        int n = (so.getCurrentPage()-1)*so.getPageSize();
        int m =so.getPageSize();
        int total = farmerRoleInfoMapper.countTotal(so.getRoleName());
        List<FarmerRoleInfoSo> list=farmerRoleInfoMapper.selectRoles(so.getRoleName(),n, m);
        Map<String  , Object> map = new Hashtable<>();
        map.put("total",total);
        map.put("data",list);
        return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED,map);
    }

    @Override
    public ResultEx getAdminRoleList() {
        List<FarmerRoleInfo> list = farmerRoleInfoMapper.selectList(
                new QueryWrapper<FarmerRoleInfo>()
                        .eq("is_delete",0)
                        .eq("is_stop",0));
        return  ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED,list);
    }

    @Transactional
    @Override
    public ResultEx updateAdminRoleInfo(FarmerRoleInfoSo so) {
        List<RolePermissionInfo> rolePermissionInfos=new ArrayList<>();
        if (ObjectUtils.isEmpty(so) || StringUtils.isEmpty(so.getFlag())) {
            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_BAD_REQUEST);
        }
        if(so.getFlag().equals("1")) {
            if("".equals(so.getRoleName()) || "".equals(so.getRoleText())){
                return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_BAD_REQUEST);
            }
            int have = this.count(new QueryWrapper<FarmerRoleInfo>()
                    .eq(StringUtils.isNotEmpty(so.getRoleName()), "role_name", so.getRoleName()));
            if(have > 0){
                return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_NO_ROLE_ERROR);
            }

            FarmerRoleInfo farmerRoleInfo = BeanConvertUtils.copyProperties(so, FarmerRoleInfo.class);
            farmerRoleInfo.setCreateTime(LocalDateTime.now());
            //保存角色信息
            farmerRoleInfoMapper.insert(farmerRoleInfo);
            //获取新增角色的主键值
            int roleId=farmerRoleInfo.getId();
            //保存角色、权限关联表
            String funId=so.getFunId();
            if(!StringUtils.isBlank(funId)){
               String[] funIds=funId.split(",");
                for(String id:funIds){
                    rolePermissionInfos.add(RolePermissionInfo.builder().roleId(roleId).funId(Integer.valueOf(id)).build());
                }
                rolePermissionInfoImpl.saveBatch(rolePermissionInfos);
            }

            return  ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED);

        }else if(so.getFlag().equals("2")){
            if (so.getId() == null || so.getId() <= 0) {
                return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_BAD_REQUEST);
            }
            FarmerRoleInfo farmerRoleInfo = BeanConvertUtils.copyProperties(so, FarmerRoleInfo.class);
            farmerRoleInfo.setCreateTime(LocalDateTime.now());
            this.updateById(farmerRoleInfo);

            //获取角色id
            int roleId=farmerRoleInfo.getId();
            //删除角色原有权限
            rolePermissionInfoMapper.delete(new QueryWrapper<RolePermissionInfo>()
                    .eq("role_id", roleId ));
            //保存角色、权限关联表
            String funId=so.getFunId();
            if(!StringUtils.isBlank(funId)){
                String[] funIds=funId.split(",");
                for(String id:funIds){
                    rolePermissionInfos.add(RolePermissionInfo.builder().roleId(roleId).funId(Integer.valueOf(id)).build());
                }
                rolePermissionInfoImpl.saveBatch(rolePermissionInfos);
            }

            return  ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED);

        }else{
            return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_BAD_REQUEST);
        }
    }

    @Override
    public List<FarmerRoleInfoVo> getRoleDownLoadList(FarmerRoleInfoSo so) {
        List<FarmerRoleInfoVo> listVo = new ArrayList<>();
        List<FarmerRoleInfo> list = farmerRoleInfoMapper.selectList(
                new QueryWrapper<FarmerRoleInfo>()
                        .like(StringUtils.isNotEmpty(so.getRoleName()), "role_name", so.getRoleName()));
        if(CollectionUtils.isNotEmpty(list) || list.size() > 0){
            for ( int i = 0 ; i<list.size() ; i++) {
                FarmerRoleInfoVo farmerRoleInfoVo = BeanConvertUtils.copyProperties(list.get(i), FarmerRoleInfoVo.class);
                LocalDateTime createTime = list.get(i).getCreateTime();
                DateTimeFormatter sf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                farmerRoleInfoVo.setCreateTime(sf.format(createTime));
                listVo.add(farmerRoleInfoVo);
            }
        }
        if(CollectionUtils.isEmpty(listVo) || listVo.size() < 0){
            return new ArrayList<>();
        }
        return  listVo;
    }

    @Override
    public ResultEx deleteUser(FarmerUserInfoSo so) {
        if(so.getId() == null || "".equals(so.getId())){
            return  ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_BAD_REQUEST);
        }
        int users = farmerUserInfoMapper.selectCount(new QueryWrapper<FarmerUserInfo>().eq("role_id", so.getId()));
        if(users > 0){
            return  ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_DELETE_ROLE_FAIL_ERROR);
        }
        int flag = farmerRoleInfoMapper.delete(new QueryWrapper<FarmerRoleInfo>().eq("id", so.getId()));
        if(flag > 0){
            return  ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_SUCCEED);
        }
        return ResultExM.builder().makeResult(ErrorCodeEnum.ERR_COMMON_FAIL);
    }

    @Override
    public ResultEx getTreeData() {
        List<FarmerPermissionInfo> list=farmerRoleInfoMapper.getTreeData();
        return ResultEx.builder().makeSuccessResult(list);

    }

    @Override
    public ResultEx queryFunByRole(FarmerUserInfoSo so) {
        try {

            List<String> list = farmerRoleInfoMapper.queryFunByRole(so.getRoleId());
            return ResultEx.builder().makeSuccessResult(list);
        } catch (Exception e) {
            return ResultEx.builder().makeFailedResult("查询失败");

        }
    }


}
